import { _decorator, Component, Button, Node, EventTouch, Sprite, Label, ProgressBar } from 'cc';
import { Game } from '../core/Game';
import { Databus } from '../core/Databus';
import { ResourceManager } from '../framework/ResourceManager';
import { EventManager } from '../core/EventManager';
import DataEventReport from '../platform/DataEventReport';
import { UserAttribute } from '../core/UserAttribute';
import { PlatformSetting } from '../platform/PlatformSetting';
import { UniformFunction } from '../platform/UniformFunction';
import { BYTEDANCE, WECHAT } from 'cc/env';
import { InterstitialAd } from '../platform/ad/InterstitialAd';
import { MatrixCustomLeftAd } from '../platform/ad/MatrixCustomLeftAd';
import { MatrixCustomRightAd } from '../platform/ad/MatrixCustomRightAd';
import { NetSoundManager } from '../framework/SoundManager';

const { ccclass, property } = _decorator;
const databus = Databus.Instance();

@ccclass('HomePage')
export class HomePage extends Component {
  private fastGameButton: Button = null;
  private friendGameButton: Button = null;
  private fancyGameButton: Button = null;
  private endlessGameButton: Button = null;

  private packBagButton: Button = null;
  private taskButton: Button = null;
  private rankingButton: Button = null;
  private moreGameButton: Button = null;
  private moreInfoButton: Button = null;
  private earnCoinButton: Button = null;
  private rewardBonusButton: Button = null;

  private userInfoImage: Node = null;
  private loadingBar: Node = null;
  private barLength = 0;
  private hasLoadHeaderImage = false;
  private showRewordBg = false;
  private gameCircleButton = null;
  onLoad(): void {
    this.fastGameButton = this.node.getChildByName('FastGameButton').getComponent(Button);
    this.friendGameButton = this.node.getChildByName('FriendGameButton').getComponent(Button);
    this.fancyGameButton = this.node.getChildByName('FancyGameButton').getComponent(Button);
    this.endlessGameButton = this.node.getChildByName('EndlessGameButton').getComponent(Button);
    this.userInfoImage = this.node.getChildByName('UserHeaderInfo').getChildByName('UserHeaderImage');
    this.loadingBar = this.node.getChildByName('LoadingProgressBar');
    this.packBagButton = this.node.getChildByName('BottomNavigation').getChildByName('BagMall').getComponent(Button);
    this.taskButton = this.node.getChildByName('BottomNavigation').getChildByName('TaskList').getComponent(Button);
    this.moreInfoButton = this.node.getChildByName('BottomNavigation').getChildByName('MoreInfo').getComponent(Button);
    this.earnCoinButton = this.node.getChildByName('TopNavigation').getChildByName('Coin').getComponent(Button);

    this.rankingButton = this.node.getChildByName('LeftNavigation').getChildByName('Ranking').getChildByName('RankingButton').getComponent(Button);
    this.moreGameButton = this.node.getChildByName('RightNavigation').getChildByName('MoreGame').getChildByName('MoreButton').getComponent(Button);
    this.rewardBonusButton = this.node.getChildByName('RewardBonus').getChildByName('BonusButton').getComponent(Button);
    
    this.fastGameButton.node.on(Button.EventType.CLICK, this.fastGameBall, this);
    this.friendGameButton.node.on(Button.EventType.CLICK, this.friendGameBall, this);
    this.fancyGameButton.node.on(Button.EventType.CLICK, this.fancyGameBall, this);
    this.endlessGameButton.node.on(Button.EventType.CLICK, this.endlessGameBall, this);
    this.packBagButton.node.on(Button.EventType.CLICK, this.toBackPackPage ,this);
    this.taskButton.node.on(Button.EventType.CLICK, this.toEarnCoinPage, this);
    this.rankingButton.node.on(Button.EventType.CLICK, this.toRankingPage, this);
    this.moreGameButton.node.on(Button.EventType.CLICK, this.toMoreGamePage, this);
    this.moreInfoButton.node.on(Button.EventType.CLICK, this.toMoreGamePage, this);
    this.earnCoinButton.node.on(Button.EventType.CLICK, this.toEarnCoinPage, this);
    this.rewardBonusButton.node.on(Button.EventType.CLICK, this.clickRewordBonus, this);
    this.userInfoImage.on(Node.EventType.TOUCH_END, this.onUserCenterPage, this);
    
    this.node.getChildByName('RewardBonus').getChildByName('IntroductSprite').getChildByName('InSideBarButton').getComponent(Button).node.on(Button.EventType.CLICK, this.clickInSideBar, this);
    this.node.getChildByName('RewardBonus').getChildByName('IntroductSprite').getChildByName('CloseButton').getComponent(Button).node.on(Button.EventType.CLICK, this.closeRewordBonus, this);
    this.loadingBar.active = false;
    this.showRewordBg = false;

    if (WECHAT) {
      const { screenWidth, screenHeight } = wx.getSystemInfoSync();
      this.gameCircleButton = wx.createGameClubButton({
        type: "image",
        icon: 'light',
        style: {
          left: 0.9 * screenWidth,
          top: 0.2 * screenHeight,
          width: 40,
          height: 40
        },
        // openlink: 'Lv-XO1OgAuqztP4pRyKfZnY2aJKe9aE1'
     })
     this.gameCircleButton.show();
    }
  }
  onDisable() {
    if (this.gameCircleButton) {
      this.gameCircleButton.hide();
    }
  }
  start() {
    EventManager.Instance().Clear();
    this.loadingBar.active = false;
    // InterstitialAd.Instance().show();
    MatrixCustomLeftAd.Instance().show();
    MatrixCustomRightAd.Instance().show();

    if (this.gameCircleButton) {
      this.gameCircleButton.show();
    }

    NetSoundManager.Instance().stopBgMusic();
  }
  update(deltaTime: number) {
    this.barLength += deltaTime;
    // 更新用户的头像信息
    this.updateUserHeader();
    if (databus.showScene.showRewardBonus) {
      this.node.getChildByName('RewardBonus').getChildByName('BonusButton').active = true;
    } else {
      this.node.getChildByName('RewardBonus').getChildByName('BonusButton').active = false;
    }
    if (this.showRewordBg) {
      this.node.getChildByName('RewardBonus').getChildByName('IntroductSprite').active = true;
    } else {
      this.node.getChildByName('RewardBonus').getChildByName('IntroductSprite').active = false;
    }
    if (this.loadingBar.active) {
      var pro = 0.5 + this.barLength / 3;
      if (pro > 100) pro = 0.99;
      this.loadingBar.getComponent(ProgressBar).progress = pro;
    }

    const coinLabel = this.node.getChildByName('TopNavigation').getChildByName('Coin').getChildByName('Label').getComponent(Label);
    coinLabel.string = `${databus.selfInfo.goldCoin}`;
  }

  fastGameBall(button: Button) {
    Game.Instance().battleCate.netBattle();
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'FastGameBall');
    databus.sceneStack.toSelectPage();
  }
  friendGameBall(button: Button) {
    Game.Instance().battleCate.frientBattle();
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'FriendGameBall');
    databus.sceneStack.toSelectPage();
    // 每次进入好友对战，则重新设置房间ID
    Game.Instance().resetRoomId();
  }
  fancyGameBall(button: Button) {
    Game.Instance().setSelfUserAttribute(databus.selfInfo);
    Game.Instance().setOppoUserAttribute(UserAttribute.newEmptyUser());
    ResourceManager.Instance().clearSpriteFrame(ResourceManager.OppoUserHeaderImage);
    Game.Instance().battleCate.fancyBattle();
    Game.Instance().gameType.eightBall();

    Game.Instance().setOutlookAttribute(databus.outlook.tableName, databus.outlook.mainBallName, databus.outlook.roomName);
    Game.Instance().setSelfUserQiuGanName(databus.outlook.ganName);

    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'FancyGameBall');
    databus.sceneStack.toRoomPage();

    this.loadingBar.active = true;
    this.barLength = 0;
  }
  endlessGameBall(button: Button) {
    Game.Instance().setSelfUserAttribute(databus.selfInfo);
    Game.Instance().setOppoUserAttribute(UserAttribute.newEmptyUser());
    ResourceManager.Instance().clearSpriteFrame(ResourceManager.OppoUserHeaderImage);
    Game.Instance().battleCate.endlessBattle();
    Game.Instance().gameType.eightBall();
    Game.Instance().setOutlookAttribute(databus.outlook.tableName, databus.outlook.mainBallName, databus.outlook.roomName);
    Game.Instance().setSelfUserQiuGanName(databus.outlook.ganName);
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'EndlessGameBall');
    databus.sceneStack.toRoomPage();
    this.loadingBar.active = true;
    this.barLength = 0;
  }
  updateUserHeader() {
    const headSpriteFrame = ResourceManager.Instance().getImageSpriteFrame(ResourceManager.SelfUserHeaderImage);

    const userHeaderSprite = this.userInfoImage.getComponent(Sprite);
    userHeaderSprite.spriteFrame = headSpriteFrame;
    this.hasLoadHeaderImage = true;

    // 更新昵称和账号
    const nickName = this.node.getChildByName('UserHeaderInfo').getChildByName('UserHeaderName').getChildByName('NickName').getComponent(Label);
    // 截取前4个字
    nickName.string = databus.selfInfo.showNickName();

    // 更新账号信息
    const levelName = this.node.getChildByName('UserHeaderInfo').getChildByName('UserLevel').getChildByName('LevelName').getComponent(Label);
    levelName.string = databus.selfInfo.playLevel.playLevelName();
  }
  onUserCenterPage(e: EventTouch) {
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'UserCenterPage');
    databus.sceneStack.toUsercenterPage();
  }
  toBackPackPage(e: EventTouch) {
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'BackPackPage');
    databus.sceneStack.toBackPackPage();
  }
  toEarnCoinPage(e: EventTouch) {
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'EarnCoinPage');
    databus.sceneStack.toEarnCoinPage();
  }
  toRankingPage(e: EventTouch) {
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'RankingPage');
    databus.sceneStack.toRankingPage();
  }
  toMoreGamePage(e: EventTouch) {
    if (PlatformSetting.isByteDance()) {
      new UniformFunction().showInfoToast('暂不支持', 1000);
      return;
    }
    DataEventReport.Instance().reportComponentEvent(databus.sceneStack.currentPageName(), 'MoreGamePage');
    databus.sceneStack.toMoreGamePage();
  }
  clickRewordBonus(e: EventTouch) {
    this.showRewordBg = true;
  }

  closeRewordBonus(e: EventTouch) {
    this.showRewordBg = false;
  }
  clickInSideBar(e: EventTouch) {
    this.showRewordBg = false;
    if (BYTEDANCE) {
      tt.navigateToScene({
        scene: "sidebar",
        success: (res) => {
          console.log("navigate to scene success");
        },
        fail: (res) => {
          console.log("navigate to scene fail: ", res);
          // 跳转失败回调逻辑
        },
      });
    }
  }
}